package com.ctcemti.mdm.project.sys.service.impl;


import com.ctcemti.mdm.common.result.Result;
import com.ctcemti.mdm.common.result.ResultEnum;
import com.ctcemti.mdm.common.result.ResultUtil;
import com.ctcemti.mdm.common.util.JWTUtil;
import com.ctcemti.mdm.common.util.RedisUtil;
import com.ctcemti.mdm.common.util.StringUtils;
import com.ctcemti.mdm.project.sys.dao.*;
import com.ctcemti.mdm.project.sys.entity.OrgOrganization;
import com.ctcemti.mdm.project.sys.entity.OrgProject;
import com.ctcemti.mdm.project.sys.entity.TreeObject;
import com.ctcemti.mdm.project.sys.service.ICompanyService;
import com.ctcemti.mdm.project.sys.service.IProjectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class ProjectService implements IProjectService {

    @Autowired
    ProjectMapper projectMapper;

    @Autowired
    RelOrganizationProjectMapper relOrganizationProjectMapper;

    @Autowired
    OrgPersonMapper orgPersonMapper;

    @Autowired
    RelPersonOrgMapper relPersonOrgMapper;

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    ICompanyService companyService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    CommonService commonService;

    @Override
    public Result insertOrUpdate(OrgProject orgProject) {
        //判断父节点不能为空
        if (!StringUtils.isNullOrEmpty(orgProject.getName().trim())) {
            OrgProject temp = new OrgProject();
            temp.setName(orgProject.getName().trim());
            //判断父节点是否为空
            if (StringUtils.isNullOrEmpty(orgProject.getOrgId())) {
                temp.setOrgId("");
            } else {
                temp.setOrgId(orgProject.getOrgId());
            }
            if (projectMapper.selectCount(temp) > 1) {
                return ResultUtil.error(ResultEnum.ZTSJ_1005);
            }
            //判断是否是修改时没有修改名字
            if (projectMapper.selectCount(temp) == 1) {
                OrgProject pro = projectMapper.selectOne(temp);
                if (!pro.getId().equals(orgProject.getId())) {
                    return ResultUtil.error(ResultEnum.ZTSJ_1005);
                }
            }
        } else {
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }

        //简称是否重复
        if (!StringUtils.isNullOrEmpty(orgProject.getShortName())) {
            OrgProject temp = new OrgProject();
            temp.setShortName(orgProject.getShortName().trim());
            temp.setOrgId(orgProject.getOrgId());
            if (projectMapper.selectCount(temp) > 1) {
                return ResultUtil.error(ResultEnum.ZTSJ_1005);
            }
            //判断是否是修改时没有修改
            if (projectMapper.selectCount(temp) == 1) {
                OrgProject pro = projectMapper.selectOne(temp);
                if (!pro.getId().equals(orgProject.getId())) {
                    return ResultUtil.error(ResultEnum.ZTSJ_1005);
                }
            }
        } else {
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }

        //判断是需要新增还是修改
        if (orgProject.getId() == null) {//新增
            //生成uuid
            orgProject.setId(UUID.randomUUID().toString());
            //保存
            projectMapper.insert(orgProject);
        } else {//修改
            projectMapper.updateByPrimaryKey(orgProject);
        }
        //刷新redis
        return ResultUtil.success();
    }

    @Override
    public Result moveTo(String orgId, String id) {
        if (StringUtils.isNullOrEmpty(orgId) || StringUtils.isNullOrEmpty(id)) {
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }
        projectMapper.updateOrg(orgId, id);
        return ResultUtil.success();
    }

    @Override
    public List<OrgProject> selectProByUserId(String token) {
        String loginname = JWTUtil.getLoginName(token);
        String loginId = JWTUtil.getLoginId(token);
        List<String> strings = new ArrayList<String>();
        //strings = orgPersonMapper.selectOrgIdByLoginId(loginId);
        List<String> list = new ArrayList<String>();

//        if("Administrator".equals(loginname)){
//            List<OrgOrganization> orgOrganizations = companyService.selectRootById();
//        }else{
//            Result<List<OrgOrganization>> byPersonId =
//        }
        if("Administrator".equals(loginname)){
            strings = orgPersonMapper.selectOrgIdByAdmin(loginId);
        }else{
            //strings = orgPersonMapper.selectOrgIdByLoginId(loginId);
            List<OrgOrganization> orgOrganizations = companyService.getByPersonId(loginId).getData();
            List<OrgOrganization> neworgOrganizations = orgPersonMapper.selectOrgTree(orgOrganizations);
            for(OrgOrganization org:neworgOrganizations){
                list.add(org.getId());
            }
            strings = orgPersonMapper.selectOrgIdByLoginId(list);
        }
        List<OrgProject> orgProjects = new ArrayList<OrgProject>();
        if(strings.size()>0){
            orgProjects = projectMapper.selectProByUserId(strings);
        }
        return orgProjects;
    }

    @Override
    public Result importPros(List<OrgProject> orgProjects) {
        return null;
    }

    @Override
    public Result delete(OrgProject orgProject) {
        projectMapper.delete(orgProject);
        return ResultUtil.success();
    }

    @Override
    public PageInfo<OrgProject> getProjectsByPid(String companyId, Integer page, Integer limit) {
        OrgProject queryParam = new OrgProject();
        queryParam.setPrjId(companyId);
        List<OrgProject> orgProjects = new ArrayList<>();
        if (StringUtils.isNullOrEmpty(companyId)) {
            return new PageInfo<>();
        }
        //根据组织ID先获取所有项目ID
        PageHelper.startPage(page, limit);
        PageHelper.orderBy("a.sort");
        orgProjects = projectMapper.getProjectsByPid(companyId);
        PageInfo<OrgProject> pageInfo = new PageInfo<OrgProject>(orgProjects);
        return pageInfo;
    }

    @Override
    public PageInfo<OrgProject> getAllProjects(Integer page, Integer limit, OrgProject entity) {
        List<OrgProject> orgProjects = new ArrayList<>();
        PageHelper.startPage(page, limit);
        PageHelper.orderBy("sort");
        Example example = new Example(OrgProject.class);
        Example.Criteria criteria = example.createCriteria();
        if(!StringUtils.isNullOrEmpty(entity.getName())){
            criteria.andLike("name","%"+entity.getName()+"%");
        }
        orgProjects = projectMapper.selectByExample(example);
        PageInfo<OrgProject> pageInfo = new PageInfo<OrgProject>(orgProjects);
        return pageInfo;
    }

    @Override
    public Result getProjectsForTree(String pId, String type, String personId) {
        List<TreeObject> result = new ArrayList<TreeObject>();
        //从redis中根据人员id获取对应的所有组织
        List<OrgOrganization> orgOrganizationsForSelected = new ArrayList<>();
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);
        if (orgOrganizationsForSelected == null || orgOrganizationsForSelected.size() == 0) {
            //
            commonService.insertComRelationToRedisByPersonId(personId);
            return ResultUtil.success(result);
        }
        //判断父节点的类型
        switch (type) {
            //公司
            case "1":
                for (OrgOrganization t : orgOrganizationsForSelected) {
                    if (t.getParentId() != null && t.getParentId().equals(pId)) {
                        //判断类型
                        //虚拟组织
                        if (t.getType().equals(3)) {
                            String count = companyMapper.countCompany(t.getId());
                            String countPro = companyMapper.countProject(t.getId());
                            //如果公司下面虚拟组织包含项目
                            if (Integer.parseInt(countPro) > 0) {
                                TreeObject treeProject = new TreeObject();
                                treeProject = setTreeObjectFromOrg(treeProject, t);
                                result.add(treeProject);
                            }
                            //如果公司下面虚拟组织包含公司
                            if (Integer.parseInt(count) > 0) {
                                TreeObject treeProject = new TreeObject();
                                treeProject = setTreeObjectFromOrg(treeProject, t);
                                result.add(treeProject);
                            }
                        }
                        //-------------下面部分为子分公司不在虚拟组织下而是父级直接是铁四局--------------
                       /* if (t.getType().equals(3)) {
                            String count = companyMapper.countProject(t.getId());
                            if (Integer.parseInt(count) > 0) {
                                TreeObject treeProject = new TreeObject();
                                treeProject = setTreeObjectFromOrg(treeProject, t);
                                result.add(treeProject);
                            }
                        }*/
                        //公司
                        if (t.getType().equals(1)) {
                            //获取虚拟组织，判断虚拟组织是否有项目，如果有加入result中
                            TreeObject treeProject = new TreeObject();
                            treeProject = setTreeObjectFromOrg(treeProject, t);
                            result.add(treeProject);
                        }
                    }
                }
                break;
            //虚拟组织
            case "3":
                for (OrgOrganization t : orgOrganizationsForSelected) {
                    if (t.getParentId() != null && t.getParentId().equals(pId)) {
                        TreeObject treeProject = new TreeObject();
                        treeProject = setTreeObjectFromOrg(treeProject, t);
                        result.add(treeProject);
                    }
                }
                break;
            //项目部
            case "4":
                //根据pId获取该项目是否为总项目
                boolean ifPrimaryProject = false;
                OrgProject o = new OrgProject();
                o.setOrgId(pId);
                List<OrgProject> checkIfParentProject = projectMapper.select(o);
                if (checkIfParentProject == null || checkIfParentProject.size() == 0) {
                    return ResultUtil.success();
                }
                //循环判断
                for (OrgProject tp : checkIfParentProject) {
                    if (tp.getPrjId() == null || tp.getPrjId().equals("")) {
                        ifPrimaryProject = true;
                        break;
                    }
                }
                //根据不同类型的项目获取
                if (ifPrimaryProject) {
                    //如果是总项目。只获取总项目
                    for (OrgProject tp : checkIfParentProject) {
                        if (tp.getPrjId() == null || tp.getPrjId().equals("")) {
                            TreeObject primaryPro = new TreeObject();
                            primaryPro = setTreeObjectFromPro(primaryPro, tp, true);
                            result.add(primaryPro);
                            continue;
                        }
                    }
                } else {
                    //如果不是总项目，添加所有项目
                    for (OrgProject tp : checkIfParentProject) {
                        TreeObject ordinaryPro = new TreeObject();
                        ordinaryPro = setTreeObjectFromPro(ordinaryPro, tp, true);
                        result.add(ordinaryPro);
                    }
                }
                break;
            //如果点击的是项目
            case "5":
                //根据总项目获取子项目或获取不到值
                OrgProject p = new OrgProject();
                p.setPrjId(pId);
                List<OrgProject> list = projectMapper.select(p);
                if (list == null || list.size() == 0) {
                    return ResultUtil.success();
                }
                for (OrgProject pTemp : list) {
                    TreeObject treeObject = new TreeObject();
                    treeObject = setTreeObjectFromPro(treeObject, pTemp, false);
                    result.add(treeObject);
                }
                break;
        }
        return ResultUtil.success(result);
    }

    private TreeObject setTreeObjectFromOrg(TreeObject treeObject, OrgOrganization organization) {
        treeObject.setId(organization.getId());
        treeObject.setPId(organization.getParentId());
        treeObject.setName(organization.getName());
        treeObject.setShortName(organization.getShortName());
        treeObject.setType(organization.getType());
        treeObject.setParent(true);
        return treeObject;
    }

    private TreeObject setTreeObjectFromPro(TreeObject treeObject, OrgProject orgProject, boolean ifPriPro) {
        treeObject.setId(orgProject.getId());
        treeObject.setPId(orgProject.getPrjId());
        treeObject.setName(orgProject.getName());
        treeObject.setShortName(orgProject.getShortName());
        treeObject.setParent(ifPriPro);
        treeObject.setType(5);
        return treeObject;
    }


}
